﻿
using Dapper;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using YaAppoint.DappperConnection;

namespace YaAppoint.DapperRepositories
{
    /// <summary>
    /// 检查项目  Dapper仓储
    /// </summary>
    public class DapperExamItemRepository(IConnectionProvider connectionProvider,
                                          IConfiguration configuration) : IDapperExamItemRepository
    {
        private readonly IConfiguration _configuration = configuration;
        private readonly IConnectionProvider _connectionProvider = connectionProvider;

        public async Task<List<HisExamItemDto>> GetListAsync(string depCode, string depName, string deviceTypeCode, string deviceTypeName)
        {
            var databaseType = _connectionProvider.GetDatabaseType();
            var connStr = _configuration["ConnectionStrings:HisDb"];
            if (string.IsNullOrWhiteSpace(connStr))
            {
                throw new BusinessException(CustomErrorCodes.NoHisConnectionNotFund);
            }
            string parmSign = databaseType.GetParameterSign();
            using var conn = _connectionProvider.GetDbConnection(connStr, databaseType);
            conn.Open();
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("depCode", depCode);
            parameters.Add("depName", depName);
            parameters.Add("deviceTypeCode", deviceTypeCode);
            parameters.Add("deviceTypeName", deviceTypeName);
            var tableName = "pacs_view_exam_item";
            string sqlStr = $@"
                                select * 
                                    from  {tableName}
                                    where (
                                            DepartmentCode  = {parmSign}depCode
                                            or
                                            DepartmentName  = {parmSign}depName
                                           )
                                        and
                                           (
                                             DeviceTypeCode = {parmSign}deviceTypeCode
                                             or
                                             DeviceTypeName = {parmSign}deviceTypeName
                                           )
                            ";
            var institutionCode = _configuration["InstitutionCode"];
            if (!string.IsNullOrWhiteSpace(institutionCode))
            {
                sqlStr += $" and InstitutionCode = {institutionCode}";
            }
            var res = (await conn.QueryAsync<HisExamItemDto>(sqlStr, parameters)).ToList();
            conn.Close();
            return res;
        }
    }
}
